package com.etrans.web.gps.business.base.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.base.domain.AreaVO;
import com.etrans.web.gps.business.base.domain.EnterpriseVO;
import com.etrans.web.gps.business.base.domain.PlatformVO;
import com.etrans.web.gps.business.base.domain.PubOrganzation;
import com.etrans.web.gps.business.base.service.EnterpriseService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.WebServiceUtil;
import com.etrans.web.gps.util.grid.FlexiGridUtil;


/**
 * 业户信息管理Controller
 * @author zhangw
 *
 */
@Controller
@RequestMapping(value="/base/enterprise/*")
public class EnterpriseController extends BaseController {
	
	private final static Logger logger = LoggerFactory.getLogger("DriverController");
	
	@Autowired
	private EnterpriseService enterpriseService;
	
	/**
	 * 页面跳转入口
	 * @return
	 */
	@RequestMapping(value="getEnterpriseManager.html")
	public ModelAndView loadDriver(){
		ModelAndView view = new ModelAndView();
		view.setViewName("views/business/base/enterprise/enterpriseManager");
		return view;
		
	}
	
	/**
	 * 加载所属区域列表
	 * @param response
	 * @param areaId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadAreaTreesExtend.html")
	public List<AreaVO> loadAreaTreesExtend(HttpServletResponse response,String areaId) {
		HashMap<String, Object> params=new HashMap<String, Object>();
		params.put("areaId", areaId);
		return enterpriseService.queryAreaTreesExtend(params);
	}
	
	/**
	 * 加载经营范围列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadBizScopeList.html")
	public List<HashMap<String,Object>> loadBizScopeList() {
		return enterpriseService.queryBizScopeList();
	}
	
	/**
	 * 加载平台列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadPlatformList.html")
	public List<PlatformVO> loadPlatformList() {
		return enterpriseService.queryPlatformList();
	}

	/**
	 * 加载发证机关列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadLssuingAuthList.html")
	public List<PubOrganzation> loadLssuingAuthList() {
		return enterpriseService.queryLssuingAuthList();
	}
	
	/**
	 * 加载经济类型列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadEconomyTypeList.html")
	public List<HashMap<String,Object>> loadEconomyTypeList() {
		return enterpriseService.queryEconomyTypeList();
	}
	
	/**
	 * 分页查询业户信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadEnterpriseList.html")
	public PageVo loadEnterpriseList(@RequestParam  String paramsGrid) {
		PageVo page = new PageVo();		
		Map<String, Object> paramMap =  FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		List<EnterpriseVO> enterpriseList = (List<EnterpriseVO>) enterpriseService.loadEnterpriseList(paramMap);	
		
		for(EnterpriseVO enterprise:enterpriseList){
			String province = enterprise.getProvince() == null ? "" : enterprise.getProvince();
			String city = enterprise.getCity() == null ? "" : enterprise.getProvince();
			enterprise.setBizLicenseNum(enterprise.getBizLicenseNum() == null ? "" : province+city+enterprise.getBizLicenseNum());
		}
		page.setRows(enterpriseList);
		page.setPage((int)paramMap.get("page"));
		page.setTotal(enterpriseService.queryEnterpriseListCount(paramMap));
		
		return page;
	}
	/**
	 * 根据用户名查找业户数量
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryEnterpriseByName.html")
	public Map<String, Object> queryEnterpriseByName(String enterpriseName) {
		Map<String, Object> result = new HashMap<>();
		Integer enterpriseId = enterpriseService.queryEnterpriseByName(enterpriseName);
		result.put("enterpriseId", enterpriseId);
		return result;
	}
	/**
	 * 判断经营许可证号是否重复
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryEnterpriseByBizLicenseNum.html")
	public Map<String, Object> queryEnterpriseByBizLicenseNum(String bizLicenseNum) {
		Map<String, Object> result = new HashMap<>();
		Integer count = enterpriseService.queryEnterpriseByBizLicenseNum(bizLicenseNum);
		result.put("code", count);
		return result;
	}
	
	/**
	 * 跳转新增界面
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "initEnterpriseForm.html")
	public ModelAndView initEnterpriseForm() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("action", "insert");
		mav.addObject("enterprise", new EnterpriseVO());
		mav.setViewName("views/business/base/enterprise/addEnterpriseForm");
		return mav;
	}	

	/**
	 * 新增和修改保存
	 * @return
	 */
	@RequestMapping(value = "saveEnterpriseForm.html")
	@ResponseBody
	public Map<String, Object> saveEnterpriseForm(String action,EnterpriseVO enterprise) {
		Map<String, Object> result = new HashMap<>();
		try {
			// 首先查看是否有重复的许可证号，保证许可证号唯一
			HashMap<String, Object> parms = new HashMap<String, Object>();
			String bizLicenseNum = enterprise.getBizLicenseNum();
			parms.put("bizLicenseNum",bizLicenseNum );
			if ("insert".equals(action)) {
				int Count = enterpriseService.queryCountByBizLicenseNum(parms);
				if (Count == 0) {
					bizLicenseNum = enterprise.getBizLicenseNum().replace(" ", "");
					enterprise.setBizLicenseNum(bizLicenseNum);
					enterpriseService.saveEnterprise(enterprise);
					result.put("code", Constant.RETURN_OK_CODE);
					result.put("msg", "保存成功");
				} else {
					// 已经重复
					result.put("code", Constant.RETURN_Repent_CODE);
					result.put("msg", "许可证号已被使用!");
				}
			}
			if ("update".equals(action)) {
				enterpriseService.updateEnterprise(enterprise);
				result.put("code", Constant.RETURN_OK_CODE);
				result.put("msg", "保存成功");
			}
			/*if (bizLicenseNum != null && !"".equals(bizLicenseNum) ) {
			}else {
				result.put("code", Constant.RETURN_Repent_CODE);
				result.put("msg", "许可证号不能为空!");
			}*/
		} catch (Exception e) {
			logger.error("", e);
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "保存失败!");
		}
		return result;
	}
	/**
	 * 回填修改信息
	 * @return
	 */
	@RequestMapping(value = "initUpdateEnterpriseForm.html")
	public String initUpdateEnterpriseForm(Model model,String enterpriseId) {
		int id = Integer.parseInt(enterpriseId);
		EnterpriseVO enterprise = enterpriseService.queryEnterpriseById(id);
		model.addAttribute("enterpriseId", enterpriseId);
		model.addAttribute("action", "update");
		model.addAttribute("enterprise", enterprise);
		return "views/business/base/enterprise/addEnterpriseForm";
	}
	/**
	 * 跳转详细页面
	 * @return
	 */
	@RequestMapping(value = "initDetailInfo.html")
	public String initDetailInfo(Model model,String enterpriseId) {
		int id = Integer.parseInt(enterpriseId);
		EnterpriseVO enterprise = enterpriseService.queryEnterpriseById(id);
		model.addAttribute("enterpriseId", enterpriseId);
		model.addAttribute("enterprise", enterprise);
		return "views/business/base/enterprise/DetailInfo";
	}

	/**
	 * 批量删除业户信息
	 * @return
	 */
	@RequestMapping(value = "delEnterpriseList.html")
	@ResponseBody
	public Map<String, Object> delEnterpriseList(String enterpriseIds) {
		Map<String, Object> result = new HashMap<>();
		try {
			if (enterpriseIds != null && !"".equals(enterpriseIds)) {
				String[] arrayEnterpriseIds = enterpriseIds.split(",");
				for (String perID : arrayEnterpriseIds) {
					enterpriseService.deleteEnterpriseByID(Integer.parseInt(perID));
					result.put("code", Constant.RETURN_OK_CODE);
					result.put("msg", "修改成功!");
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "删除失败!");
		}
		return result;
	}
	/**
	 * 导出报表
	 * @param response
	 * @param request
	 * @param paramsGrid 前端json格式的参数
	 * @param colModel 表头
	 * @param title 标题
	 * @param imgsrc 图片url,如果为null则不加载图片页
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="exportEnterprises.html")
	@ResponseBody
	public void exportDriver(HttpServletResponse response,HttpServletRequest request, String colModel,
			String title,String imgsrc){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> paramMap=getReqParameters();
		String fromNumber = paramMap.get("fromNumber") == null ? "0" : String.valueOf(paramMap.get("fromNumber"));
		String pageSize = paramMap.get("pageSize") == null ? "0" : String.valueOf(paramMap.get("pageSize"));
		paramMap.replace("fromNumber", Integer.valueOf(fromNumber));
		paramMap.replace("pageSize", Integer.valueOf(pageSize));
		List<String> colModelList = JSON.parseObject(colModel, List.class);	
		List<EnterpriseVO> result =enterpriseService.loadEnterpriseList(paramMap);
		List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
		for(int i=0;i<result.size();i++){
			HashMap<String, Object> map = new HashMap<String, Object>();
			EnterpriseVO  enterprsie=(EnterpriseVO)result.get(i);
			map.put("name",enterprsie.getName() == null ? "" : enterprsie.getName());
			map.put("areaName",enterprsie.getAreaName() == null ? "" : enterprsie.getAreaName());
			map.put("platformName",enterprsie.getPlatformName() == null ? "" : enterprsie.getPlatformName());
			map.put("bizScope",enterprsie.getBizScope() == null ? "" : enterprsie.getBizScope());
			String province = enterprsie.getProvince() == null ? "" : enterprsie.getProvince();
			String city = enterprsie.getCity() == null ? "" : enterprsie.getProvince();
			map.put("bizLicenseNum",enterprsie.getBizLicenseNum() == null ? "" : province+city+enterprsie.getBizLicenseNum());
			String startTime = enterprsie.getInvalidStartTime() == null ? "" : String.valueOf(sdf.format(enterprsie.getInvalidStartTime()));
			String endTime = enterprsie.getInvalidEndTime() == null ? "" : String.valueOf(sdf.format(enterprsie.getInvalidEndTime()));
			map.put("invalidTime", "".equals(startTime) && "".equals(endTime) ? "" : startTime + " 至  " + endTime);
			map.put("lssuingAuth",enterprsie.getLssuingAuth() == null ? "" : enterprsie.getLssuingAuth());
			map.put("corporate",enterprsie.getCorporate() == null ? "" : enterprsie.getCorporate());
			map.put("phone",enterprsie.getPhone() == null ? "" : enterprsie.getPhone());
			map.put("email",enterprsie.getEmail() == null ? "" : enterprsie.getEmail());
			map.put("contact",enterprsie.getContact() == null ? "" : enterprsie.getContact());
			map.put("economy_type_name",enterprsie.getEconomy_type_name() == null ? "" : enterprsie.getEconomy_type_name());
			map.put("hasSync",enterprsie.getHas_sync() == null ? "未同步" :("1".equals(String.valueOf(enterprsie.getHas_sync()))? "已同步" : "未同步"));
			map.put("enableSms",enterprsie.getEnable_sms() == null ? "停用" :("1".equals(String.valueOf(enterprsie.getEnable_sms()))? "启用":"停用"));
			map.put("enableEmail",enterprsie.getEnable_email() == null ? "停用" :("1".equals(String.valueOf(enterprsie.getEnable_email()))? "启用":"停用"));
			//map.put("sysPwd",enterprsie.getSysPwd() == null ? "" : enterprsie.getSysPwd());
			map.put("rowver",String.valueOf(enterprsie.getRowver())== null ? "" : sdf.format(enterprsie.getRowver()));
			rows.add(map);
		}	
		int index=-1;
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		exportExl(request, response,title, removeHeadName(colModelList,index,-1),rowsList,null);
	}
	
	// 获取运政业户信息
	@RequestMapping(value = "getOwnerInfo.html")
	@ResponseBody
	public Map<String, Object> getOwnerInfo(@RequestParam String yhmc, String xkzh,String ziparea) {
		Map<String, Object> result = new HashMap<>();
		try {
			result =WebServiceUtil.getOwnerInfoXml(yhmc,xkzh,ziparea);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "操作失败!");
		}
		return result;
	}
	
	// 同步运政业户信息
	@RequestMapping(value = "synOwnerInfo.html")
	@ResponseBody
	public Map<String, Object> synOwnerInfo(String[] vehicleIds) {
		Map<String, Object> result = new HashMap<>();
		try {
			for (int i = 0; i < vehicleIds.length; i++) {
				Map<String,Object> mo = enterpriseService.queryOwnerVoById(Integer.valueOf(vehicleIds[i]));
				if(mo.get("name")!=null&&mo.get("license")!=null&&mo.get("code")!=null){
					boolean flag = enterpriseService.synOwnerInfo(mo.get("name").toString(),mo.get("license").toString(),mo.get("code").toString());
					if(flag){
						result.put("code", Constant.RETURN_OK_CODE);
						result.put("msg", "操作成功!");
					}else{
						result.put("code", 1);
						result.put("msg", "同步接口数据失败!");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "操作失败!");
		}
		return result;
	}
}
